package com.skit.main.ui.add

import android.app.DatePickerDialog
import android.app.ProgressDialog
import android.app.TimePickerDialog
import android.content.Intent
import android.os.Bundle
import android.provider.MediaStore
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.TimePicker
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.gson.Gson
import com.skit.common.base.BaseActivity
import com.skit.common.bean.ActivityBean
import com.skit.common.bean.Department
import com.skit.common.config.RetrofitClient
import com.skit.common.config.RouteConfig
import com.skit.common.http.HttpUtils
import com.skit.common.manager.UserManager
import com.skit.common.utils.FileUtil
import com.skit.common.utils.ToastUtils
import com.skit.main.R
import com.skit.main.adapter.ImageAdapter
import com.skit.main.fragment.EditBottomSheetFragment
import com.skit.common.retrofit.ActivityProtocol
import com.skit.vip.oss.service.OSSConfig
import com.skit.vip.oss.service.OssService
import kotlinx.android.synthetic.main.main_activity_add.*
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

/**
 * @author shuike <a href="mailto:shuike007@gmail.com">Contact me.</a>
 * @version 1.0
 * @since  2020/5/28
 */

@Route(path = RouteConfig.MainRoute.MAIN_ACTIVITY_CREATE)
class AddActivity : BaseActivity() {
    private var activityStartTime: Long = System.currentTimeMillis() + (1000 * 60 * 60 * 24 * 2)
    private var activityEndTime: Long = System.currentTimeMillis() + (1000 * 60 * 60 * 24 * 7)

    private var applicationStartTime: Long = System.currentTimeMillis()
    private var applicationEndTime: Long = System.currentTimeMillis() + (1000 * 60 * 60 * 24 * 2)

    var activityDescriptionText: String = "无活动描述"
    var adminScore = 0.0
    var stuScore = 0.0

    private val format = SimpleDateFormat("MM月dd日 HH:mm", Locale.getDefault())

    private var boutiqueBooleanExtra: Boolean = false
    private var typeBean: ActivityBean.TypeBean? = null
    private var description: String = "无活动描述"
    val imgList: MutableList<String> = ArrayList<String>()
    val activityImgList: MutableList<String> = ArrayList<String>()
    var scope: Int = 0
    lateinit var adapter: ImageAdapter
    private val scopeArray = arrayOf("全校", "校区", "学院")
    private var department: Department? = null

    companion object {
        const val RC_CHOOSE_PHOTO = 2
        const val TYPE_ACTIVITY = 3
        const val TAG = "AddActivity"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.main_activity_add)
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        initViews()

    }

    private fun initViews() {
        if (UserManager.user == null) {
            ToastUtils.showToast("请登录")
            finish()
            return
        }
        department = UserManager.user?.userInfo?.department
        organizerTV.text = resources.getString(R.string.main_organizer, department?.departmentName)

        rangeTV.text = resources.getString(R.string.application_scope, scopeArray[scope])
        applicationScope.setOnClickListener {
            range()
        }

        activityDescription.setOnClickListener {
            val newInstance = EditBottomSheetFragment.newInstance(description)
            newInstance.show(supportFragmentManager, "请输入活动描述")
            newInstance.setDoneListener {
                description = it
            }
        }

        activityTypeTV.text =
            resources.getString(
                R.string.main_activity_type,
                if (typeBean == null) "未设定" else typeBean?.name
            )
        activityType.setOnClickListener {
            val intent: Intent = Intent(this, ActivityTypeActivity::class.java)
            startActivityForResult(intent, TYPE_ACTIVITY)
        }

        imgList.add("add")
        adapter = ImageAdapter(imgList)
        recyclerView.adapter = adapter
        recyclerView.isNestedScrollingEnabled = false
        recyclerView.layoutManager = GridLayoutManager(this, 3)

        adapter.onClickListener = View.OnClickListener { choosePhoto() }
        adapter.onDeleteClick = object : (Int) -> Unit {
            override fun invoke(p1: Int) {
                imgList.removeAt(p1)
                if (imgList.size > 0 && imgList[0] == "add") {
                    activityImgList.removeAt(p1 - 1)
                } else {
                    activityImgList.removeAt(p1)
                }
//                activityImgList.removeAt(p1)
//                adapter.notifyItemRemoved(p1)
                adapter.notifyChanged()
            }
        }

        activityTimeTV.text = resources.getString(
            R.string.main_activity_time,
            format.format(activityStartTime),
            format.format(activityEndTime)
        )
        activityTime.setOnClickListener {
            activityStartTime()
        }

        activityApplyTimeTV.text = resources.getString(
            R.string.main_apply_time,
            format.format(applicationStartTime),
            format.format(applicationEndTime)
        )
        activityApplyTime.setOnClickListener {
            activityApplyStartTime()
        }
    }

    private fun activityStartTime() {
        val calendar = Calendar.getInstance()
        val dialog = DatePickerDialog(
            this,
            DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
                run {
                    timePicker { view, hourOfDay, minute ->
                        run {
                            calendar.set(year, month, dayOfMonth, hourOfDay, minute)
                            val format1 = format.format(calendar.time)
                            activityStartTime = calendar.timeInMillis
                            activityEndTime()
                        }
                    }
                }
            },
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        )
        dialog.show()
    }

    private fun activityApplyStartTime() {
        val calendar = Calendar.getInstance()
        val dialog = DatePickerDialog(
            this,
            DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
                run {
                    timePicker { view, hourOfDay, minute ->
                        run {
                            calendar.set(year, month, dayOfMonth, hourOfDay, minute)
                            val format1 = format.format(calendar.time)
                            applicationStartTime = calendar.timeInMillis
                            activityApplyEndTime()
                        }
                    }
                }
            },
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        )
        dialog.show()
    }

    private fun activityApplyEndTime() {
        val calendar = Calendar.getInstance()
        val dialog = DatePickerDialog(
            this,
            DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
                run {
                    timePicker { view, hourOfDay, minute ->
                        run {
                            calendar.set(year, month, dayOfMonth, hourOfDay, minute)
                            val format1 = format.format(calendar.time)
                            applicationEndTime = calendar.timeInMillis

                            activityApplyTimeTV.text = resources.getString(
                                R.string.main_apply_time,
                                format.format(applicationStartTime),
                                format.format(applicationEndTime)
                            )
                        }
                    }
                }
            },
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        )
        dialog.show()
    }

    private fun activityEndTime() {
        val calendar = Calendar.getInstance()
        val dialog = DatePickerDialog(
            this,
            DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
                run {
                    timePicker { view, hourOfDay, minute ->
                        run {
                            calendar.set(year, month, dayOfMonth, hourOfDay, minute)
                            val format1 = format.format(calendar.time)
                            activityEndTime = calendar.timeInMillis

                            activityTimeTV.text = resources.getString(
                                R.string.main_activity_time,
                                format.format(activityStartTime),
                                format.format(activityEndTime)
                            )
                        }
                    }
                }
            },
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        )
        dialog.show()
    }

    fun timePicker(listener: (TimePicker, Int, Int) -> Unit) {
        val calendar = Calendar.getInstance()
        val dialog = TimePickerDialog(
            this,
            listener,
            calendar.get(Calendar.HOUR),
            calendar.get(Calendar.MINUTE),
            true
        )
        dialog.show()
    }

    fun range() {
        val builder: AlertDialog.Builder =
            AlertDialog.Builder(this)
                .setTitle("报名范围").setItems(scopeArray) { dialog, which ->
                    run {
                        scope = which
                        rangeTV.text =
                            resources.getString(R.string.application_scope, scopeArray[which])
                    }
                }
        builder.show()
    }

    fun submit() {
        val user = UserManager.user!!
        when {
            user == null -> {
                return
            }
            activityName.text.isNullOrEmpty() -> {
                ToastUtils.showToast("活动名称为空")
                return
            }
            typeBean == null -> {
                ToastUtils.showToast("未设定活动类型")
                return
            }
            eventLocation.text.isNullOrEmpty() -> {
                ToastUtils.showToast("活动地点为空")
                return
            }
            applyNum.text.isNullOrEmpty() -> {
                ToastUtils.showToast("活动人数为空")
                return
            }
            applyNum.text.toString().toInt() < 3 -> {
                ToastUtils.showToast("活动人数不能少于3人")
                return
            }
        }

//        val filter = imgList.filter { it != "add" }
//        val array = arrayOfNulls<String>(filter.size)
//
//        for (index in filter.indices) {
//            array[index] = filter[index]
//        }

        val activityBean = ActivityBean()
        activityBean.activityName = activityName.text.toString()
        activityBean.activityImages = activityImgList
        activityBean.activityDescription = description
        activityBean.quotaNum = Integer.parseInt(applyNum.text.toString())
        activityBean.range = scope
        activityBean.signUpStartTime = applicationStartTime
        activityBean.signUpEndTime = applicationEndTime

        activityBean.startTime = activityStartTime
        activityBean.endTime = activityEndTime
        activityBean.type = typeBean
        activityBean.boutique = boutiqueBooleanExtra
        activityBean.adminScore = adminScore
        activityBean.stuScore = stuScore
        activityBean.organizer = user?.userInfo?.department
        activityBean.organizerID = user?.userInfo?.department?.id!!
        activityBean.founderID = user?.id!!
        activityBean.eventLocation = eventLocation.text.toString()


        val service = RetrofitClient.getService(ActivityProtocol::class.java)
        val call =
            service.addActivity(user?.token, Gson().toJson(activityBean))
        HttpUtils.doRequest(call) {
            if (it == null || !it.isSuccess) {
                if (it != null) ToastUtils.showToast(it.msg)
                return@doRequest
            }
            ToastUtils.showToast("提交成功")
            finish()
        }
/*
        val progressDialog = ProgressDialog(this)
        progressDialog.setCancelable(false)
        progressDialog.show()
        BmobFile.uploadBatch(array, object : UploadBatchListener {
            override fun onSuccess(p0: MutableList<BmobFile>?, p1: MutableList<String>?) {
                if (p1?.size == array.size) {
                    val activityBean = ActivityBean()
                    activityBean.activityName = activityName.text.toString()
                    activityBean.activityImages = p1
                    val service = RetrofitClient.getService(ActivityProtocol::class.java)
                    val call =
                        service.addActivity(UserManager.user?.token, Gson().toJson(activityBean))
                    HttpUtils.doRequest(call) {
                        if (it == null || !it.isSuccess) {
                            if (it != null) ToastUtils.showToast(it.msg)
                            return@doRequest
                        }
                        ToastUtils.showToast("提交成功")
                    }
                }
            }

            override fun onProgress(p0: Int, p1: Int, p2: Int, p3: Int) {
                progressDialog.setMessage("正在上传图片$p0/$p2")
            }

            override fun onError(p0: Int, p1: String?) {
                progressDialog.setCancelable(true)
                progressDialog.setMessage("上传失败")
            }

        })
*/

    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == 0) {
            submit()
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        val submit = menu?.add(0, 0, 0, "发布")
        submit?.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
//        submit?.isEnabled = false
        return true
    }

    private fun choosePhoto() {
        val intentToPickPic =
            Intent(Intent.ACTION_PICK, null)
        intentToPickPic.setDataAndType(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            "image/*"
        )
        startActivityForResult(intentToPickPic, RC_CHOOSE_PHOTO)
    }

    override fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        data: Intent?
    ) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            RC_CHOOSE_PHOTO -> {
                if (data == null) return
                val uri = data.data
                val filePath: String = FileUtil.getFilePathByUri(this, uri)
                if (!TextUtils.isEmpty(filePath)) {
                    upload(filePath)
                }
            }

            TYPE_ACTIVITY -> {
                if (data == null) return
                typeBean =
                    data.getSerializableExtra("typeBean") as ActivityBean.TypeBean
                boutiqueBooleanExtra = data.getBooleanExtra("boutique", false)

                adminScore = data.getDoubleExtra("adminScore", 0.0)
                stuScore = data.getDoubleExtra("stuScore", 0.0)
                activityTypeTV.text =
                    resources.getString(R.string.main_activity_type, typeBean?.name)
            }
        }
    }


    private fun upload(filePath: String) {
        val progressDialog = ProgressDialog(this)
        progressDialog.setMessage("正在上传。。")
        progressDialog.show()
        val ossService = OssService(this, OSSConfig.END_POINT, OSSConfig.BUCKET_NAME)
        ossService.initOSSClient()
        ossService.imageUpload(
            this,
            OSSConfig.OssFolder.ACTIVITY + File(filePath).name,
            filePath
        )
        ossService.setFinishCallback(object : OssService.FinishCallback {
            override fun onFinish(urls: MutableList<String>?) {

            }

            override fun onFinish(url: String) {
                runOnUiThread {
                    progressDialog.dismiss()
                    activityImgList.add(url)
                    imgList.add(filePath)
                    adapter.notifyChanged()
                }
            }

            override fun onProgressCallback(progress: Double, position: Int) {

            }

        })
        ossService.setProgressCallback { progress, url ->
            progressDialog.progress = progress.toInt()
            progressDialog.setMessage("上传中: ${progress.toInt()}/100%")
            if (progress.toInt() == 100) {
//                progressDialog.dismiss()
//                activityImgList.add(url)
//                imgList.add(url)
//                adapter.notifyChanged()
            } else {
//                progressDialog.progress = progress.toInt()
//                progressDialog.setMessage("上传中: ${progress.toInt()}/100%")

            }
        }
//        HttpUtils.uploadFile(filePath, object : com.skit.common.http.UploadFileListener() {
//            override fun done(url: String?) {
//                if (url != null) {
//                    progressDialog.dismiss()
//                    activityImgList.add(url)
//                    imgList.add(url)
//                    adapter.notifyChanged()
//                } else {
//                    progressDialog.dismiss()
//                    Toast.makeText(
//                        this@AddActivity,
//                        "上传失败：",
//                        Toast.LENGTH_SHORT
//                    ).show()
//                }
//            }
//
//        })
/*        val bmobFile = BmobFile(File(filePath))
        bmobFile.uploadblock(object : UploadFileListener() {
            override fun done(e: BmobException?) {
                if (e == null) {
                    progressDialog.dismiss()
                    activityImgList.add(bmobFile.fileUrl)
                    imgList.add(bmobFile.fileUrl)
                    adapter.notifyChanged()
                } else {
                    Log.d(TAG, "done: " + e.message)
                    progressDialog.dismiss()
                    Toast.makeText(
                        this@AddActivity,
                        "上传失败：",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        })*/
/*        bmobFile.upload(object : UploadFileListener() {
            override fun done(e: BmobException) {
                if (e == null) {
                    progressDialog.dismiss()
                    Toast.makeText(
                        this@AddActivity,
                        "上传成功" + bmobFile.getFileUrl(),
                        Toast.LENGTH_SHORT
                    ).show()
                    activityImgList.add(bmobFile.fileUrl)
                    imgList.add(bmobFile.fileUrl)
                    adapter.notifyChanged()
                } else {
                    Log.d(TAG, "done: " + e.message)
                    progressDialog.dismiss()
                    Toast.makeText(
                        this@AddActivity,
                        "上传失败：" + e.errorCode,
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        })*/
    }
}